#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@FileName  :systemReceive.py
@desc      :
@Author    :Young
@IDE       :PyCharm
@Time      :2022-09-25 8:49
'''

from PyQt5 import QtWidgets
from PyQt5.QtCore import QTimer
import serial
import serial.tools.list_ports

#自定义
from Database import *
from WorldCup import Ui_MainWindow



def open_port(port, bps, timeout):  # 打开串口
    ret = False
    #print(6666666)
    try:
        # 打开串口，并得到串口对象
        ser = serial.Serial(port, bps, timeout=timeout)
        # 判断是否打开成功
        if ser.is_open:
            ret = True
            print("打开串口操作成功！")
            print(port + "打开了")
    except Exception as e:
        print("---异常---：", e)
    return ret, ser


class Pyqt_Serial(QtWidgets.QWidget,Ui_MainWindow):
    def __init__(self):
        super(Pyqt_Serial, self).__init__() # **
        self.receivePort = None  # 接收串口
        self.receiveCondition = False  # 接收串口状态
        self.receiveIDInfo = None   #接收到的ID卡卡号信息
        self.secondBlockDisply = None  #第二个框显示内容
        self.setupUi(self)
        self.bind()
        self.timer = QTimer(self)  # 初始化一个定时器
        self.setWindowTitle("南非世界杯预选赛")


    def bind(self):
        '''
        把按钮的点击事件和具体函数绑定
        :return: None
        '''
        self.Checkin.clicked.connect(self.check_in)
        self.Reset.clicked.connect(self.reset)



    def check_in(self):
        '''
        Checkin按钮对应函数，完成打开接收端口，开始接收数据的功能
        :return:
        '''
        self.open_receive_port()
        self.start_receive()

    def reset(self):
        '''
        Reset按钮对应函数，完成接收端口的关闭，及接收串口数据的清除
        :return:
        '''
        self.close_receive_port()
        self.clear_receive()

    def check_ID_info(self):
        '''
        对接收到的ID卡号信息进行判定，给出结果提示
        :return: None
        '''
        if check_ticket_info(self.receiveIDInfo) == 2:  #该类用户已注册，但还未检票
            userName = return_username_by_ID(self.receiveIDInfo)
            #tip = "尊敬的" + userName + "：您的门票检票成功，请您通过!"
            tip = 'Dear' + userName + 'Your ticket checked in successfully, please pass!'
            self.textBrowser.append(tip)
        elif check_ticket_info(self.receiveIDInfo) == 1: #该类用户已注册，已检票，再检票为重复检票
            print("该票用户已注册，已经检票")
            userName = return_username_by_ID(self.receiveIDInfo)
            #tip = "尊敬的" + userName + "：您的门票已检，重复检票，检票失败!"
            tip = 'Dear' + userName + ':Your ticket has been checked, repeated ticket, ticket failed!'
            self.textBrowser.append(tip)
        else:  #result == 0  #该类用户没有注册，数据库没有该用户信息
            #tip = self.receiveIDInfo + ":该票据用户未注册，无效票，检票失败！"
            tip = self.receiveIDInfo +": The ticket of user is not registered, no valid ticket, ticket failed!"
            self.textBrowser.append(tip)
        # time.sleep(3)
        # self.clear_receive()


    def open_receive_port(self):
        '''
        打开接收端口
        :return:
        '''
        port = 'COM3'  # 接收接口的名字
        bps = 9600  # 接受接口的波特率
        timeout = None  # 接收接口的连接时间
        # print(2222222)
        self.receiveCondition, self.receivePort = open_port(port, bps, timeout)

    def close_receive_port(self):
        '''
        关闭数据接收端口
        :return: None
        '''
        try:
            # 判断是否打开成功
            if self.receivePort.is_open:
                self.receivePort.close()  # 关闭数据接收端口
                self.receiveCondition = False  # 更新接收端口状态
        except Exception as e:
            print("---异常---：", e)

    def start_receive(self):
        '''
        开始接收数据
        :return:None
        '''
        print("开始接收数据！")
        if self.receiveCondition:
            print("接收连接已建立！")
            text = self.receivePort.read(24).decode("gbk")  # 从串口中读入数据
            print(text)
            self.receiveData.append(text)  # 将数据显示在第一个窗口中
            self.receiveIDInfo = text[16:]
            # 对接收到的ID卡号信息进行判定，给出结果提示
            self.check_ID_info()
        else:
            print("接收情况未建立！")

    def clear_receive(self):
        '''
        清理接收数据界面， 全部清除
        :return:None
        '''
        self.receiveData.clear()
        self.textBrowser.clear()





